package cn.com.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class HttpPostUtil {

	public static Map<String, String> payPost(Map<String, String> map) {

		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();

			HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");

			List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();

			Element root = DocumentHelper.createElement("xml");
			root.addElement("appid").addText(map.get("appid"));
			root.addElement("body").addCDATA(map.get("body"));
			root.addElement("mch_id").addText(map.get("mch_id"));
			root.addElement("nonce_str").addText(map.get("nonce_str"));
			root.addElement("notify_url").addText(map.get("notify_url"));
			root.addElement("openid").addText(map.get("openid"));
			root.addElement("out_trade_no").addText(map.get("out_trade_no"));
			root.addElement("spbill_create_ip").addText(map.get("spbill_create_ip"));
			root.addElement("total_fee").addText(map.get("total_fee"));
			root.addElement("trade_type").addText(map.get("trade_type"));
			root.addElement("sign").addCDATA(map.get("sign"));

			String xmlStr = root.asXML();
			System.out.println(xmlStr + "&&&&&&&&&&&&&&&&&&&&&&");
			post.setEntity(new StringEntity(xmlStr, "UTF-8"));

			response = httpClient.execute(post);
			InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8");
			Map<String, String> result = MessageUtil.parseXmlMessage(reader);
			return result;
		} catch (Exception ex) {

			ex.printStackTrace();
		} finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
